package org.zhang.boot;

import org.zhang.boot.util.FileUtil;
import org.zhang.boot.util.OnionClassLoader;
import org.zhang.boot.util.StringUtil;

import java.io.File;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Constructor;
import java.net.URL;

public class JavaAgent {

    public static void premain(String agentArgs, Instrumentation inst) {
        try {
            String coreJarPath = FileUtil.getJarFile().getPath();
            if ("classes".equals(coreJarPath.substring(coreJarPath.lastIndexOf(File.separator) + 1))) {
                //某些开发环境下（例如 IDE 中运行时），可能会返回编译输出的目录而不是 JAR 文件，把classes替换成jar包
                coreJarPath = StringUtil.replaceLast(coreJarPath, "classes", "agent-boot-1.0-SNAPSHOT-jar-with-dependencies.jar");
            }
            System.out.println("包路径:" + coreJarPath);
            File agentJarFile = new File(coreJarPath);

            final ClassLoader agentLoader = new OnionClassLoader(new URL[]{agentJarFile.toURI().toURL()});

            Class<?> transFormer = agentLoader.loadClass("org.zhang.core.asm.MyClassFileTransformer");

            Constructor<?> constructor = transFormer.getConstructor(String.class);
            Object instance = constructor.newInstance(agentArgs);

            inst.addTransformer((ClassFileTransformer) instance);
        } catch (Exception e) {
            System.out.println("JavaAgent入口报错");
        }
    }
}
